class HttpHelper {
    constructor(){

    };
    request(option,callback) {
        if (String(option) !== '[object Object]') return undefined;
        option.method = option.method ? option.method.toUpperCase() : 'GET';
        option.data = option.data || {};
        
        let arr = Object.keys(option.data); 
        if(arr.length > 0 ){
            let formData = [];
            for (var key in option.data) {
                formData.push(''.concat(key, '=', option.data[key]))
            }
            option.data = formData.join('&');
            if (option.method === 'GET') {
                option.url += ''.concat('?', option.data)
            }
        }
        
        let xhr = cc.loader.getXMLHttpRequest();
        xhr.timeout = 5000;
        xhr.open(option.method, option.url, true);

        if (option.method === 'POST') {
            xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded')
        }
        if (cc.sys.isNative){
            xhr.setRequestHeader("Accept-Encoding","gzip,deflate","text/html;charset=UTF-8");
        }
        xhr.onreadystatechange = function() {
            if(xhr.readyState === 4 && (xhr.status >= 200 && xhr.status < 300)){
                try {
                    // var ret = JSON.parse(xhr.responseText);
                    var ret = xhr.responseText;
                    if(callback !== null){
                        callback(null, ret);
                    }                        /* code */
                } catch (e) {
                    callback(e, null);
                }
                finally{
                    
                }
            }else{
                game.openTip({
                    content:'网络连接失败,请重试',
                    ok_call:null,
                    cancel_call:null
                });
            }
        };
        
        if(cc.vv && cc.vv.wc){
            //cc.vv.wc.show();
        }
        try{
            xhr.send(option.method === 'POST' ? option.data : null)
        }catch(e){
            game.openTip({
                content:'网络连接失败,请重试',
                ok_call:null,
                cancel_call:null
            });
        };
    }
    static getInstance(){
        if(!this.instance){
            this.instance = new HttpHelper();
        };
        return this.instance;
    };
}
module.exports = HttpHelper;